package cn.xiaoming.car.server.consumer;

import cn.xiaoming.car.pojo.order.pojo.entity.OrderTbl;
import cn.xiaoming.car.server.ex.ServiceException;
import cn.xiaoming.car.server.jsonresult.ServiceCode;
import cn.xiaoming.car.server.mapper.OrderTblMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import static cn.xiaoming.car.server.IOrderService.*;

@RocketMQMessageListener(
        consumerGroup = "consumer-group-order",
        topic = "expire-order",
        selectorExpression = "*"
)
@Component
@Slf4j
public class ExpireOrderConsumer implements RocketMQListener<String> {
    @Autowired
    RedisTemplate<String,Object> redisTemplate;

    @Autowired
    OrderTblMapper orderTblMapper;


    @Override
    public void onMessage(String message) {
        // 查询订单状态，如果订单状态还是0，
        // 表示并没有支付，修改订单状态为已过期
        log.debug("来到处理过期订单的消费");
        OrderTbl orderTbl =(OrderTbl) redisTemplate.opsForValue().get(message);
        System.out.println(orderTbl);
        if (orderTbl==null){
            throw new ServiceException(ServiceCode.ERR_UNKNOWN,"未知异常");
        }
        //删除redis中的数据
        Boolean delete = redisTemplate.delete(message);
        if (delete!=true){
            throw new ServiceException(ServiceCode.ERR_UNKNOWN,"删除redis中的数据失败");
        }
        if (INITIAL.equals(orderTbl.getStatus())){
            orderTbl.setStatus(EXPIRE);
            int i = orderTblMapper.updateById(orderTbl);
            if (i!=1){
                throw new ServiceException(ServiceCode.ERR_UNKNOWN,"向数据库更新过期订单失败");
            }
            log.debug("成功更新订单状态到过期状态");
        }
        log.debug("消费者执行完毕了！");
    }
}
